<?php

namespace app\job;

use think\Exception;
use think\Log;
use think\queue\Job;

class EmailJob
{
    public function fire(Job $job, $data)
    {
        $result = $this->sendEmail($data['email'], $data['content']);
        // 2. 处理任务结果
        if ($result) {
            Log::info("邮件发送成功: {$data['email']}");
            $job->delete(); // 删除任务
        } else {
            // 重试机制
            if ($job->attempts() > 3) {
                Log::error("邮件发送失败: {$data['email']}，已重试3次");
                $job->delete();
            } else {
                $job->release(10); // 10秒后重试
            }
        }
    }

    private function sendEmail($email, $content)
    {
        try {
            throw new Exception('发生失败');
            // 模拟发送邮件
            echo "Sending email to $email with content: $content\n";
            return true; // 假设发送成功
        } catch (\Exception $e) {
            Log::error("邮件异常: " . $e->getMessage());
            return false;
        }
    }
}